package br.ufpe.cin.analysis.plugin.models;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.jfree.data.general.Dataset;

import br.ufpe.cin.analysis.plugin.entities.Process;


public abstract class ChartDataset<T extends Dataset> {
	
	private Process process;
	private T jFreeChartDataset;
	private File xmlFile;
	
	
	public ChartDataset(String xmlFileName) throws JAXBException, IOException
	{
		this.xmlFile = new File(xmlFileName);
		this.loadProcess();
	}
	
	public ChartDataset(Process process)
	{
		this.process = process;
		this.xmlFile = new File(this.process.getName()+".xml");
		this.makeJFreeChartDataset();
	}
	
	public ChartDataset(Process process, String xmlFile)
	{
		this.process = process;
		this.xmlFile = new File(xmlFile);
		this.makeJFreeChartDataset();
	}
	
	public ChartDataset()
	{
		this.process = null;
		this.xmlFile = null;
		this.jFreeChartDataset = null;
	}
	
	
	public abstract void makeJFreeChartDataset();
	
	public void loadProcess() throws JAXBException, IOException
	{
		
		FileInputStream in = new FileInputStream( this.xmlFile );

		JAXBContext context = JAXBContext.newInstance(Process.class);

		Unmarshaller unmarshaller = context.createUnmarshaller();

		this.process = (Process)unmarshaller.unmarshal(in);
		
		in.close();
		
		this.makeJFreeChartDataset();
	

	}
	
	public void storeProcess() throws JAXBException, IOException
	{
		FileOutputStream out = new FileOutputStream( this.xmlFile );
		
		JAXBContext context = JAXBContext.newInstance(Process.class);
		
		Marshaller marshaller = context.createMarshaller();
		
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		
		marshaller.marshal(this.process,out);
		
		out.close();
		
	}

	public Process getProcess() {
		return process;
	}

	public void setProcess(Process process) {
		this.process = process;
		this.xmlFile = new File(this.process.getName()+".xml");
		this.makeJFreeChartDataset();
		
	}

	public T getJFreeChartDataset() {
		return jFreeChartDataset;
	}

	public void setJFreeChartDataset(T freeChartDataset) {
		jFreeChartDataset = freeChartDataset;
	}

	public File getXmlFile() {
		return xmlFile;
	}

	public void setXmlFile(String xmlFileName) throws JAXBException, IOException {
		this.xmlFile = new File(xmlFileName);
		
		this.loadProcess();
	}
	
	

}
